/**
 * 管理员账户信息管理模块
 */
const express = require('express')
const admin = express.Router()

// 导入数据库
const db = require('../../utils/db')
// 导入加密模块
const getSha1 = require('../../utils/crypo')

// 指定导航开启
const curNav = 1

// 获取管理员列表
admin.get('/list', (req, res) => {
   db.query('SELECT * FROM admin_users ORDER BY id DESC', (error, results, fields) => {
      if (error) throw err
      res.render('admin/admin_list', {
         curNav: curNav,
         user: req.session.uname || 'xxx',
         data: results
      })
   })
})

// 添加管理员用户
admin.get('/add', (req, res) => {
   res.render('admin/admin_add', {
      curNav: curNav,
      user: req.session.uname || 'xxx'
   })
})
admin.post('/doadd', (req, res) => {
   const {uname, pwd} = req.body
   const sql = `INSERT INTO admin_users(uname, pwd) VALUES('${uname}', '${getSha1(pwd)}')`
   console.log(sql)
   db.query(sql, (err, result, fields) => {
      if (err) throw err
      if (result.affectedRows > 0) {
         res.send(`<script>alert('添加成功~'); window.location.href='/admin/list'</script>`)
      } else {
         res.send(`<script>alert('添加失败~'); window.location.href='/admin/add'</script>`)
      }
   })
})

// 更新管理员用户
admin.get('/update', (req, res) => {
   res.render('admin/admin_update', {
      curNav: curNav,
      data: req.query,
      user: req.session.uname || 'xxx'
   })
})
admin.post('/doupdate', (req, res) => {
   const {id, uname, pwd} = req.body
   const sql = `UPDATE admin_users SET uname='${uname}',pwd='${getSha1(pwd)}' WHERE id=${id}`
   db.query(sql, (err, result) => {
      if (err) throw err
      if (result.affectedRows > 0) {
         res.send(`<script>alert('更新成功~'); window.location.href='/admin/list'</script>`)
      } else {
         res.send(`<script>alert('添加失败~'); window.location.href='/admin/update?id=${id}&uname=${uname}&pwd=${pwd}'</script>`)
      }
   })
})

// 删除用户
admin.get('/del', (req, res) => {
   const {uid} = req.query
   const sql = `DELETE FROM admin_users WHERE id=${uid - 0}`
   db.query(sql, (error, result, fields) => {
      if (error) throw error
      if (result.affectedRows > 0) {
         res.json({status: 200, msg: 'ok'})
      } else {
         res.json({status: 200, msg: 'no'})
      }
   })
})

// 获取首页
admin.get('/index', (req, res) => {
   res.render('admin/admin_index', {
      curNav: '',
      user: req.session.uname || ''
   })
})
admin.get('/admindata', async (_, res) => {
   const tables = {
      'admin_users': '管理员数量',
      'users': '用户数量',
      'shoplists': '商家数量',
      'goods': '食品数量',
      'comments': '评价数量',
      'orders_goods': '订单数量'
   }
   const dataArr = []
   for (let key in tables) {
      let value = await selectData(key)
      dataArr.push({value: value, name: tables[key]})
   }
   res.json({msg: 'ok', data: dataArr})
})
function selectData(tableName) {
   // 封装查询数据库函数
   const sql = `SELECT COUNT(*) FROM ${tableName}`
   return new Promise((resolve, reject) => {
      db.query(sql, (err, result) => {
         if (result.length > 0) return resolve(result[0]['COUNT(*)'] - 0)
         resolve('')
      })
   })
}

// 搜索功能
admin.get('/search', (req, res) => {
   const {kwd} = req.query
   db.query('SELECT * FROM admin_users', (error, results) => {
      // console.log(results)
      if (results.length > 0) {
         results = results.filter((item) => {
            return item.uname.includes(kwd)
         })
      }
      res.render('admin/adminsearch', {
         curNav: curNav,
         user: req.session.uname || 'xxx',
         data: results
      })
   })
})

module.exports = admin